/**

 @Name：layuiAdmin 内容系统
 @Author：star1029
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */

layui.define(['table', 'form','upload'], function(exports){
  var $ = layui.$
  ,admin = layui.admin
  ,view = layui.view
  ,table = layui.table
  ,form = layui.form
  ,upload = layui.upload;
  
  //商品管理
    table.render({
      elem: '#LAY-app-content-list'
      ,url: '../../goods/finAll.do' //模拟接口
      ,cols: [[
        {type: 'checkbox'}
        ,{field: 'goods_id', title: '商品ID'}
        ,{field: 'goods_name', title: '商品名称'}
  		,{field: 'price', title: '价格'}
  		,{field: 'picture', title: '图片',width:130,templet:function(d){
			  return "<img src='/file/"+d.picture+"' lay-event='upload'  />";
		 }}
  		,{field: 'description', title: '描述'}
  		,{field: 'stock', title: '库存'}
  		,{field: '', title: '商品类型' ,templet: function(d){
        return d.category.category_name
		  }
		}
        ,{field: '', title: '是否上架',templet:function(d){
			  if(d.sale==1){
				  return '<input type="checkbox" param="'+d.goods_id+'" lay-filter="putOn" name="sale" lay-skin="switch" checked  lay-text="是|否">';
			  }else{
				  return '<input type="checkbox" param="'+d.goods_id+'" lay-filter="putOn" name="sale" lay-skin="switch"   lay-text="是|否">';
			  }
		}}
  		,{field: '', title: '是否推荐',templet:function(d){
			  if(d.recommend==1){
				  return '<input type="checkbox" param="'+d.goods_id+'" lay-filter="today" name="recommend" lay-skin="switch" checked  lay-text="是|否">';
			  }else{
				  return '<input type="checkbox" param="'+d.goods_id+'" lay-filter="today" name="recommend" lay-skin="switch"   lay-text="是|否">';
			  }
		}}
        ,{title: '操作',  width: 150 ,toolbar: '#table-content-list'}
      ]]
      ,page: true
      ,limit: 10
      ,limits: [10, 15, 20, 25, 30]
    });
	
	 //监听上下架开关事件
	  form.on('switch(putOn)', function(data){
		  console.log(data.elem); //得到checkbox原始DOM对象
		  console.log(data.elem.checked); //开关是否开启，true或者false
		  console.log(data.value); //开关value值，也可以通过data.elem.value得到
		  console.log(data.othis); //得到美化后的DOM对象
		  
		  //attr设置或读取一个jquery对象的属性值，prop只有一个参数时是读取，2个参数时是设置
		  $.post(
			"../../goods/putOn.do",
			{
				id:$(data.elem).attr("param"),
				sale:data.elem.checked?1:0
			},function(res){
				if(res==1){
					layer.msg("操作成功");
				}else{
					layer.msg("操作失败");
				}
			},'json'
		  );
		}); 
		
	 //监听推荐/取消推荐开关事件
	  form.on('switch(today)', function(data){
		  console.log(data.elem); //得到checkbox原始DOM对象
		  console.log(data.elem.checked); //开关是否开启，true或者false
		  console.log(data.value); //开关value值，也可以通过data.elem.value得到
		  console.log(data.othis); //得到美化后的DOM对象
		  
		  $.post(
					"../../goods/today.do",
			{
				id:$(data.elem).attr("param"),
				recommend:data.elem.checked?1:0
			},function(res){
				if(res==1){
					layer.msg("操作成功");
				}else{
					layer.msg("操作失败");
				}
			},'json'
		  );
		  
		}); 
    
    //监听工具条
    table.on('tool(LAY-app-content-list)', function(obj){
      var data = obj.data;
      if(obj.event === 'del'){
        layer.confirm('确定删除此商品吗？', function(index){
          obj.del();
          layer.close(index);
		  $.post("../../goods/del.do?id="+data.goods_id);
        });
      }else if(obj.event === 'upload'){
		admin.popup({
	        title: '修改主图片'
	        ,area: ['600px', '600px']
	        ,id: 'LAY-popup-content-upload'
	        ,success: function(layero, index){
	          view(this.id).render('app/content/upload', data).done(function(){
	        	console.log(data)//当前行数据
	        	var path ;//存储上传文件路径
	        	//显示预览图
	        	$("#upload").attr("src","/file/"+data.picture);
	        	//绑定upload组件
	        	var uploadInst = upload.render({
        		    elem: '#test1' //绑定元素
        		    ,url: '../../goods/upload.do' //上传接口
        		    ,done: function(res){
        		      //上传完毕回调
        		    	path = res.data;
        		    	$("#upload").attr("src","/file/"+path);
        		    	
        		    }
        		    ,error: function(){
        		      //请求异常回调
        		    	layer.msg("上传失败，请重新上传");
        		    }
        		});
	        	
	            form.render(null, 'layuiadmin-app-form-list');
	            
	            //监听提交
	            form.on('submit(layuiadmin-app-form-submit)', function(d){
	              var field = d.field; //获取提交的字段

	              //提交 Ajax 成功后，关闭当前弹层并重载表格
	              //$.ajax({});
	              $.post(
	            	"../../goods/uadatePicture.do",
	            	{
	            		id:data.goods_id,
	            		picture:path
	            	},function(res){
	            		layui.table.reload('LAY-app-content-list'); //重载表格
	  	              	layer.close(index); //执行关闭
	            	},"json"
	              );
	               
	            });
	          });
	        }
	      });
    } else if(obj.event === 'edit'){
        admin.popup({
          title: '编辑文章'
          ,area: ['550px', '550px']
          ,id: 'LAY-popup-content-edit'
          ,success: function(layero, index){
            view(this.id).render('app/content/listform', data).done(function(){
				//加载分类信息
				$.post(
					"../../findAllcategory.do",
					function(res){
						//console.log(res);
						$(res.data).each(function(){
							//创建一个下拉选项
							var option = $('<option value="'+this.category_id+'">'+this.category_name+'</option>');
							//将下拉选项追加到下拉框中
							$("#category_id2").append(option);
						});
						
						form.render('select'); //刷新select选择框渲染
						//回显数据
						form.val("layuiadmin-app-form-list", data);
					},'json'
				);
              form.render(null, 'layuiadmin-app-form-list');
              //监听提交
			   form.on('submit(layuiadmin-app-form-submit)', function(data){
                var field = data.field; //获取提交的字段
  
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                //$.ajax({});
				$.post(
						"../../goods/edit.do",
						field,
						function(res){
							if(res==1){
								layui.table.reload('LAY-app-content-list'); //重载表格
								layer.close(index); //执行关闭 
							}
						},'json'
					  );
                layui.table.reload('LAY-app-content-list'); //重载表格
                layer.close(index); //执行关闭 
              });
			  
			  
            });
          }
        });
      }
    });

  //分类管理
  table.render({
    elem: '#LAY-app-content-tags'
    ,url: '../../findAllcategory.do' //模拟接口
    ,cols: [[
      {type: 'numbers', fixed: 'left'}
      ,{field: 'category_id', width: 100, title: 'ID', sort: true}
      ,{field: 'category_name', title: '分类名', minWidth: 100}
      ,{field: 'parent_id', title: '父分类', minWidth: 100}
      ,{field: 'state', title: '状态', minWidth: 100}
      ,{title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#layuiadmin-app-cont-tagsbar'}
    ]]
	  ,page: true
	  ,limit: 10
	  ,limits: [10, 15, 20, 25, 30]
      ,text: '对不起，加载出现异常！'
  });
  
  //监听工具条
  table.on('tool(LAY-app-content-tags)', function(obj){
    var data = obj.data;
    if(obj.event === 'del'){
      layer.confirm('确定删除此分类？', function(index){
        $.post(
          "../../delcategory.do?category_id="+data.category_id,
          function(res){
            if(res>0){
              obj.del();
              layer.close(index);
            }
          },"json"
        );
        });
    } else if(obj.event === 'edit'){
      admin.popup({
        title: '编辑分类'
        ,area: ['450px', '200px']
        ,id: 'LAY-popup-content-tags'
        ,success: function(layero, index){
          view(this.id).render('app/content/tagsform', data).done(function(){        
           console.log(data)
            form.render(null, 'layuiadmin-form-tags');
            form.val("layuiadmin-form-tags", data);
            //监听提交
			//回显数据
			form.val("layuiadmin-app-form-list", data);
            form.on('submit(layuiadmin-app-tags-submit)', function(data){
              
              var field = data.field; //获取提交的字段     
              //提交 Ajax 成功后，关闭当前弹层并重载表格
              //$.ajax({});
              $.post(
                "../../editcategory.do",
                field,
				
                function(res){
                 
                  if(res>0){                     
                    layui.table.reload('LAY-app-content-tags'); //重载表格
                    layer.close(index); //执行关闭 
                  }
				 
                },"json"
                );
            });
          
          });
        }
      });
    }




  });

    //订单管理
    table.render({
      elem: '#LAY-app-content-comm'
      ,url: '../../admin/orders/findAllorders.do' //模拟接口
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        ,{field: 'orders_id', width: 100, title: '订单号', sort: true}
        ,{field: 'orders_time', title: '下单时间', minWidth: 180}
        ,{templet: '<div>{{d.users.user_name}}</div>', title: '下单人', minWidth: 100}
        ,{field: 'state', title: '订单状态', width: 100,templet: function(d){
  			if(d.state == 0){return "未付款"}else if(d.state == 1){
  				return "未发货"}else if(d.state == 2){
  				return "已发货"}else if(d.state == 3){
  					return "已收货"}else if(d.state == 4){
  						return "交易完成"}else if(d.state == 9){
  						return "已关闭"}
  		}}
      ,{field: 'total_money', title: '订单金额', width: 130, sort: true}
      ,{field: '', title: '收货地址', width: 380 ,templet: function (d) {
    	  function showWare(res1,res2,res3,res4,phone,name){
    		    var str = "姓名："+name+" 手机号："+phone+"地址"+res1+res2+res3+res4;
    		    return str;
    		}
    	     return showWare(d.address.province,d.address.city,d.address.country,d.address.details,d.address.phone,d.users.user_name);
      }}
        ,{title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-content-com'}
      ]]
      ,page: true
      ,limit: 10
      ,limits: [10, 15, 20, 25, 30]
      ,text: '对不起，加载出现异常！'
    });
    
    //监听工具条
    table.on('tool(LAY-app-content-comm)', function(obj){
      var data = obj.data;
      if(obj.event === 'del'){
        layer.confirm('确定删除此条评论？', function(index){
          obj.del();
          layer.close(index);
        });
      }else if(obj.event === 'details'){//订单详情
        admin.popup({
            title: '订单详情'
            ,area: ['800px', '500px']
            ,id: 'LAY-popup-content-comm'
            ,success: function(layero, index){
              view(this.id).render('app/content/orderdetails', data).done(function(){
                //加载订单详情数据
                table.render({
                elem: '#demo'
                ,url: '../../findOrder_detail.do?orders_id='+data.orders_id //数据接口
                ,cols: [[ //表头
                  {field: '', title: '图片',width:130,templet:function(d){
                       return "<img src='/file/"+d.g.picture+"' lay-event='upload'  />";
                     }}
                  ,{field: '', title: '商品名',templet:function(d){
                    return d.g.goods_name;
                  }} 
                  ,{field: '', title: '单价',templet:function(d){
                    return d.g.price;
                  }} 
                  ,{field: 'num', title: '购买数量'}
                  ,{field: '', title: '小计',templet:function(d){
                    return d.g.price*d.num;
                  }}
                ]]
              });
              });
            }
          });
        }else if(obj.event === 'edit'){
        admin.popup({
          title: '编辑评论'
          ,area: ['450px', '300px']
          ,id: 'LAY-popup-content-comm'
          ,success: function(layero, index){
            view(this.id).render('app/content/contform', data).done(function(){
              form.render(null, 'layuiadmin-form-comment');
              
              //监听提交
              form.on('submit(layuiadmin-app-com-submit)', function(data){
                var field = data.field; //获取提交的字段
  
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                //$.ajax({});
                layui.table.reload('LAY-app-content-comm'); //重载表格
                layer.close(index); //执行关闭 
              });
            });
          }
        });
      }
    });
  
  exports('contlist', {})
});